var socketOpen = false
var tt
var lockReconnect = false
var messageHandler

var websocket = {
  init: function(url) {
    var websocketUrl = url.replace('http://', 'ws://')
    websocketUrl = websocketUrl.replace('https://', 'wss://')
    uni.connectSocket({
        url: websocketUrl
    })

    uni.onSocketMessage(function(e) {
      heartCheck.start()
      if (e.data === '') {
        console.log('收到pong')
        return
      }
      uni.$emit('websocket-msg', e.data)
    })

    uni.onSocketClose(function() {
      console.log('连接关闭，开始重连')
      socketOpen = false
      reconnect(url)
    })

    uni.onSocketOpen(function(res) {
      console.log('连接成功，开始心跳')
      socketOpen = true
      heartCheck.start()
    })

    uni.onSocketError(function(res) {
      console.log('连接出错，开始重连')
      socketOpen = false
      reconnect(url)
    })
  },

  isOpen: function() {
      return socketOpen
  }
}

function reconnect(url) {
  if (lockReconnect) {
    return
  }
  lockReconnect = true
  tt && clearTimeout(tt)
  tt = setTimeout(function() {
    console.log('执行断线重连...')
    websocket.init(url, messageHandler)
    lockReconnect = false
  }, 4000)
}

/**
 * 心跳检测
 * @type {{serverTimeoutObj: null, timeoutObj: null, start: heartCheck.start, timeout: number}}
 */
var heartCheck = {
  timeout: 1000 * 60,
  timeoutObj: null,
  serverTimeoutObj: null,
  start: function() {
    console.log('开始心跳检测')
    var self = this
    this.timeoutObj && clearTimeout(this.timeoutObj)
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
    this.timeoutObj = setTimeout(function() {
      console.log('心跳检测...')
      uni.sendSocketMessage({
        data: ''
      })
      self.serverTimeoutObj = setTimeout(function() {
        if (!socketOpen) {
          uni.closeSocket()
        }
      }, self.timeout)
    }, this.timeout)
  }
}

export default websocket
